<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable style="width: 200px;">
                <el-option v-for="category in categoryList" :key="category.id" :label="category.categoryName"
                  :value="category.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="分组" prop="groupName">
              <el-select v-model="queryParams.groupName" placeholder="请选择分组" clearable style="width: 200px;">
                <el-option v-for="group in productGroupList" :key="group.id" :label="group.groupName"
                  :value="group.groupName" />
              </el-select>
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="productList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column type="index" width="70" label="序号" align="center"/> -->
        <el-table-column label="图片" align="center" prop="productImg" width="90">
          <template #default="scope">
            <image-preview :src="scope.row.productImg" width="60px" height="60px" />
          </template>
        </el-table-column>
      
        <el-table-column label="名称" align="center" prop="name" />
          <el-table-column label="规格" align="center" prop="spec" width="120" />
        <!-- <el-table-column label="ID" align="center" prop="id" v-if="true" /> -->
        <!-- <el-table-column label="序号" align="center" prop="sort" /> -->
        <!-- <el-table-column label="关联主体ID" align="center" prop="subjectId" /> -->
        <el-table-column label="分类" align="center" prop="categoryId">
          <template #default="scope">
            {{ getCategoryName(scope.row.categoryId) }}
          </template>
        </el-table-column>
        <el-table-column label="分组" align="center" prop="productGroupInfo.groupName" />


        <!-- <el-table-column label="进货价" align="center" prop="purchasePrice" /> -->


        <el-table-column label="单位" align="center" prop="unit" width="60" />
        <el-table-column label="单价" align="center" prop="unitPrice" width="120" />
        <el-table-column label="库存" align="center" prop="stock" width="80" />
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="100">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改产品信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="productFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option v-for="category in categoryList" :key="category.id.toString()" :label="category.categoryName"
              :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="分组" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择分组" filterable clearable>
            <el-option v-for="group in productGroupList" :key="group.id" :label="group.groupName" :value="group.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="产品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="销售单价" prop="unitPrice">
          <el-input v-model="form.unitPrice" placeholder="请输入销售单价" />
        </el-form-item>
        <el-form-item label="进货价" prop="purchasePrice">
          <el-input v-model="form.purchasePrice" placeholder="请输入进货价" />
        </el-form-item>
        <el-form-item label="产品图片" prop="productImg">
          <ComponentUploadImage v-model="form.productImg" returnType="url" />
          <!-- <ImageUpload 
            v-model="form.productImg" 
            :limit="1" 
            :file-size="5" 
            :file-type="['png', 'jpg', 'jpeg']"
          /> -->
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="规格" prop="spec">
          <el-input v-model="form.spec" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序序号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product" lang="ts">
import ComponentUploadImage from '@/components/ImageUpload/imageUpload.vue';

import { listMyProduct, getProduct, delProduct, addProduct, updateProduct } from '@/api/product';
import { ProductVO, ProductQuery, ProductForm } from '@/api/product/types';
import { listMyProductCategory } from '@/api/productCategory';
import { ElMessage } from 'element-plus';
import { ProductCategoryVO } from '@/api/productCategory/types';
import { listProductGroup } from '@/api/productGroup';
import { ProductGroupVO } from '@/api/productGroup/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const productList = ref<ProductVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
// 初始化分类列表为空数组
const categoryList = ref<ProductCategoryVO[]>([]);
const productGroupList = ref<ProductGroupVO[]>([]);

const queryFormRef = ref<ElFormInstance>();
const productFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ProductForm = {
  id: undefined,
  subjectId: undefined,
  categoryId: undefined,
  groupId: undefined,
  sort: undefined,
  name: undefined,
  unitPrice: undefined,
  purchasePrice: undefined,
  productImg: undefined,
  unit: undefined,
  spec: undefined,
  stock: undefined,
  creatorId: undefined
};
const data = reactive<PageData<ProductForm, ProductQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    subjectId: undefined,
    categoryId: undefined,
    groupName: undefined,
    sort: undefined,
    name: undefined,
    unitPrice: undefined,
    purchasePrice: undefined,
    productImg: undefined,
    unit: undefined,
    spec: undefined,
    stock: undefined,
    creatorId: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '产品唯一ID不能为空', trigger: 'blur' }],
    subjectId: [{ required: true, message: '关联主体ID不能为空', trigger: 'blur' }],
    categoryId: [{ required: true, message: '分类ID不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
    unitPrice: [{ required: true, message: '销售单价不能为空', trigger: 'blur' }],
    // purchasePrice: [{ required: true, message: '进货价不能为空', trigger: 'blur' }],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 获取产品分类列表 */
const getCategoryList = async () => {
  try {
    console.log('开始获取分类数据...');
    const response = await listMyProductCategory();
    console.log('分类API返回数据:', response);
    
    // 根据实际API返回格式处理数据
    if (response && response.code === 200) {
      // 实际API格式：{code: 200, rows: [], total: 8, msg: '查询成功'}
      if (Array.isArray(response.rows)) {
        categoryList.value = response.rows;
        console.log('成功加载分类数据，共', response.rows.length, '条');
      } else if (Array.isArray(response.data)) {
        // 兼容其他可能的格式
        categoryList.value = response.data;
      } else {
        categoryList.value = [];
        ElMessage.warning('分类数据格式不正确');
      }
    } else if (Array.isArray(response)) {
      // 直接返回数组的情况
      categoryList.value = response;
    } else {
      categoryList.value = [];
      ElMessage.warning('分类数据获取失败');
    }
    
    console.log('处理后的分类列表:', categoryList.value);
  } catch (error) {
    console.error('获取分类列表失败:', error);
    ElMessage.error('获取分类数据失败');
    // 保留测试数据，确保UI正常显示
    if (categoryList.value.length === 0) {
      categoryList.value = [
        { id: '1', categoryName: '电子产品', parentId: 0, subjectId: 0, sort: 1 },
        { id: '2', categoryName: '办公用品', parentId: 0, subjectId: 0, sort: 2 }
      ];
    }
  }
};

const getProductGroupList = async () => {
  try {
    const res: any = await listProductGroup();
    if (Array.isArray(res)) {
      productGroupList.value = res;
    } else if (res && Array.isArray(res.rows)) {
      productGroupList.value = res.rows;
    } else {
      productGroupList.value = [];
    }
  } catch (error) {
    console.error('获取分组列表失败:', error);
    productGroupList.value = [];
  }
};

/** 查询产品信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMyProduct(queryParams.value);
  productList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 获取分类名称 */
const getCategoryName = (categoryId: string | number) => {
  if (!categoryList.value || !Array.isArray(categoryList.value)) {
    return categoryId || '-';
  }
  const category = categoryList.value.find(cat => cat.id === categoryId);
  return category ? category.categoryName : categoryId || '-';
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  productFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProductVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加产品信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ProductVO) => {
  await getCategoryList();
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getProduct(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改产品信息';

};

/** 提交按钮 */
const submitForm = () => {
  productFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateProduct(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addProduct(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProductVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除产品信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delProduct(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/product/export',
    {
      ...queryParams.value
    },
    `product_${new Date().getTime()}.xlsx`
  );
};

onMounted(async () => {
  // 初始化分类与分组列表
  categoryList.value = [];
  productGroupList.value = [];
  
  try {
    await Promise.all([
      getCategoryList(),
      getProductGroupList()
    ]);
    
    getList();
  } catch (error) {
    console.error('初始化数据失败:', error);
    getList();
  }
});

onUpdated(async() => {
  // 初始化分类与分组列表
  categoryList.value = [];
  productGroupList.value = [];
  
  try {
    await Promise.all([
      getCategoryList(),
      getProductGroupList()
    ]);
    
    getList();
  } catch (error) {
    console.error('初始化数据失败:', error);
    getList();
  }
});
</script>
